//
//  SettingViewController.m
//  SouthChina
//
//  Created by Mr.Y on 14-10-9.
//  Copyright (c) 2014年 科创. All rights reserved.
//

#import "PersonalCenterViewController.h"
#import "PersonalCenterTableViewCell.h"
#import "PersonalInforViewController.h"
#import "AddFriendViewController.h"
#import "ZbarReaderViewController.h"
#import "FeedbackViewController.h"
#import "TakePhotoController.h"
#import "SetViewController.h"
#import "ContactDao.h"
#import "AddButtonPullDownView.h"
#import "TouristViewController.h"
#import "CreateGroupViewController.h"
#import "selectMemberViewController.h"
#define LABEL_HEIGHT 20
#define LABEL_WIDTH 60

@interface PersonalCenterViewController ()<UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate,UIAlertViewDelegate>
{
    UIScrollView *_scrollView;
    BOOL _ispulldown;

}
@property (strong, nonatomic) TakePhotoController * takephoto;
@property (strong, nonatomic) NSArray * titles;
@property (strong, nonatomic) UIButton * headImageBtn;
@property (strong, nonatomic) UIImageView * headImage;//头像
@property (strong, nonatomic) AddButtonPullDownView * addbuttonview;
@end

@implementation PersonalCenterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];

}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    _addbuttonview = [[AddButtonPullDownView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    _addbuttonview.delegate = self;
    [_addbuttonview addTarget:self action:@selector(addbuttonviewbtn:) forControlEvents:UIControlEventTouchUpInside];

    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, TITLE_BAR_HEGIHT+(YNEW), SCREEN_WIDTH, SCREEN_HEIGHT-TABBARHEIGHT-50)];
    [self.view addSubview:_scrollView];
    
    [self addTitleBarWithBackBtn:@"我" needReturn:YES];
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(270.0f, (YNEW)+5, 40.0f, 30.0f);
    [rightBtn addTarget:self action:@selector(showRightBtnView:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setImage:[UIImage imageNamed:@"addfriend_group_flag"] forState:UIControlStateNormal];
    rightBtn.imageEdgeInsets = UIEdgeInsetsMake ( 5 ,  10 , 5 , 10 );
    [self.titlebar addSubview:rightBtn];

    
    _headImageBtn = [[UIButton alloc] initWithFrame:CGRectMake(25, 18, 60, 60)];
    [_headImageBtn addTarget:self action:@selector(changeHeadImage:) forControlEvents:UIControlEventTouchUpInside];
    [_headImageBtn setTitle:@"" forState:UIControlStateNormal];
    [_headImageBtn setBackgroundColor:[UIColor clearColor]];
    [_scrollView addSubview:_headImageBtn];
    
    _headImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
    [_headImage setBackgroundColor:[UIColor clearColor]];
    
    NSString *headStr = [DE getGlobalVar:LOGIN_USER_HEADIMG] == nil?@"":[DE getGlobalVar:LOGIN_USER_HEADIMG];
    NSURL *url= [NSURL URLWithString: [headStr hasPrefix:@"http"]?headStr:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,headStr]];

    [_headImage setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
    _headImage.layer.masksToBounds = YES;
    _headImage.layer.cornerRadius = 8.0;
    [_headImageBtn addSubview:_headImage];
    
    _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(70+_headImageBtn.frame.origin.x,10, 200, LABEL_HEIGHT)];
    NSString * str = [NSString stringWithFormat:@"%@(%@)",[DE getGlobalVar:LOGIN_USER_NAME]== nil?@"":[DE getGlobalVar:LOGIN_USER_NAME],[DE getGlobalVar:LOGIN_USER_TYPE] ==nil?@"":[[DE getGlobalVar:LOGIN_USER_TYPE] isEqualToString:@"T"]?@"教职工":@"学生"];
    _nameLabel.text =str;
    [_scrollView addSubview:_nameLabel];
    
    
    _collegeDetailLabel = [[UILabel alloc] initWithFrame:CGRectMake(_nameLabel.frame.origin.x,_nameLabel.frame.origin.y+LABEL_HEIGHT, 200, LABEL_HEIGHT)];
    _collegeDetailLabel.font = [UIFont boldSystemFontOfSize:13.0f];
    _collegeDetailLabel.textColor = BASIC_BLUE_COLOR;
    _collegeDetailLabel.text = [DE getGlobalVar:LOGIN_USER_DEPT]== nil?@"":[DE getGlobalVar:LOGIN_USER_DEPT];
    [_scrollView addSubview:_collegeDetailLabel];
    
    _majorDetailLabel = [[UILabel alloc] initWithFrame:CGRectMake(_nameLabel.frame.origin.x,_collegeDetailLabel.frame.origin.y+LABEL_HEIGHT, 200, LABEL_HEIGHT)];
    _majorDetailLabel.font = [UIFont boldSystemFontOfSize:13.0f];
    _majorDetailLabel.textColor = BASIC_BLUE_COLOR;
    _majorDetailLabel.text = [DE getGlobalVar:LOGIN_USER_PROFNAME]==nil?@"":[DE getGlobalVar:LOGIN_USER_PROFNAME];
    [_scrollView addSubview:_majorDetailLabel];
    
    _classDetailLabel = [[UILabel alloc] initWithFrame:CGRectMake(_nameLabel.frame.origin.x,_majorDetailLabel.frame.origin.y+LABEL_HEIGHT, 200, LABEL_HEIGHT)];
    _classDetailLabel.font = [UIFont boldSystemFontOfSize:13.0f];
    _classDetailLabel.textColor = BASIC_BLUE_COLOR;
    _classDetailLabel.text = [DE getGlobalVar:LOGIN_USER_CLASS]==nil?@"":[DE getGlobalVar:LOGIN_USER_CLASS];
    [_scrollView addSubview:_classDetailLabel];

    _titles = @[@[@"个人信息"],@[@"同步通讯录"],@[@"设置"]];
    _setTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, _classDetailLabel.frame.origin.y+LABEL_HEIGHT, SCREEN_WIDTH, 165) style:UITableViewStyleGrouped];
    _setTableview.delegate = self;
    _setTableview.dataSource = self;
    _setTableview.bounces = NO;
    _setTableview.backgroundColor = [UIColor whiteColor];
    _setTableview.backgroundView = nil;
    [_scrollView addSubview:_setTableview];
    UIImage *img=[UIImage imageNamed:@"blue_btn_normal.png"];
    img=[img stretchableImageWithLeftCapWidth:20 topCapHeight:20];
    //注销
    UIButton * submitBtn = [[UIButton alloc] initWithFrame:CGRectMake(10,self.view.frame.size.height-155, (SCREEN_WIDTH)-20, 35)];
    [submitBtn setBackgroundImage:img forState:UIControlStateNormal];
    [submitBtn addTarget:self action:@selector(cancellation:) forControlEvents:UIControlEventTouchUpInside];
    [submitBtn setTitle:@"注销" forState:UIControlStateNormal];
    [self.view addSubview:submitBtn];
    //退出
    UIButton * closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(10,self.view.frame.size.height-110, (SCREEN_WIDTH)-20, 35)];
    [closeBtn setBackgroundImage:img forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(exitBtn:) forControlEvents:UIControlEventTouchUpInside];
    [closeBtn setTitle:@"退出" forState:UIControlStateNormal];
    [self.view addSubview:closeBtn];

    
    _scrollView.bounces = NO;
    [_scrollView setBackgroundColor:[UIColor whiteColor]];
    [_scrollView setShowsHorizontalScrollIndicator:NO];
    [_scrollView setShowsVerticalScrollIndicator:NO];
    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, _setTableview.frame.origin.y+_setTableview.frame.size.height+10);

    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _titles.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray * arr = [self.titles objectAtIndex:section];
    return arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"PersonalCenterTableViewCell";
    PersonalCenterTableViewCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
        UIImageView * aseryImage = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-40, 12, 20, 20)];
        aseryImage.image = [UIImage imageNamed:@"select_right.png"];
        [cell addSubview:aseryImage];
    }
    cell.titleLabel.text = _titles[indexPath.section][indexPath.row];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];//选中后颜色消失
    switch (indexPath.section) {
        case 0:
            if (indexPath.row == 0) {
                PersonalInforViewController * personalinformation = [[PersonalInforViewController alloc] init];
                [kAppDelegate.iCSDrawerController.navigationController pushViewController:personalinformation animated:NO ];
            }
            break;
        case 1:
            if (indexPath.row == 0) {
            
                [self refreshAdBookForced];
            }
            break;
        case 2:
            if (indexPath.row == 0) {
                SetViewController * setviewcontroller = [[SetViewController alloc] init];
                [kAppDelegate.iCSDrawerController.navigationController pushViewController:setviewcontroller animated:NO ];
                
            }
            break;
        default:
            break;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5;
}

-(void)cancellation:(id)sender
{
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您确定退出当前登录账号?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 102;
    [alert show];
}

-(void)exitBtn:(id)sender
{
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您确定要退出吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 101;
    [alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1 && alertView.tag == 101) {
        exit(1);
    }
    else if (buttonIndex == 1 && alertView.tag == 102)
    {
        
        [MBProgressHUD showHUDAddedTo:self.view prompt:@"正在登出..." animated:YES];
        NSDictionary *dict = [[NSDictionary alloc] init];
        [DE serverCall:@"loginOut" params:dict callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            [DE unload];

            DE.userId=@"";
            DE.userPassword=@"";
            [DE setGlobalVar:LOGIN_USER_ID value:@""];
            kAppDelegate.mqttState = MQTT_NO_CONNECT;
            [DE setGlobalVar:LOGIN_USER_PASSWORD value:@""];
            
            TouristViewController *info = [[TouristViewController alloc] init];
            [kAppDelegate.iCSDrawerController.navigationController setViewControllers:@[info] animated:YES];
        }];
    }
   
}
//调用手机相册
-(void)changeHeadImage:(id)sender
{
    _takephoto = [TakePhotoController new];
    _takephoto.type = TakePhotoFromPhotoLibrary;
    _takephoto.isEdit = YES;
    __weak PersonalCenterViewController *ctl = self;
    _takephoto.blockComplete = ^(UIImage * image,NSDictionary*fileMap){
 
        [UploadFile uploadFileWithFilePath:[fileMap objectForKey:@"file"] servicePath:@"HEAD_IMG" params:fileMap calback:^(BOOL success, int code, NSString *desc, NSDictionary *netdata, NSDictionary *params) {
            
            if (success) {
                [DE setGlobalVar:LOGIN_USER_HEADIMG value:[netdata objectForKey:@"URL"]];
                NSDictionary *params = @{@"user_id":DE.userId,@"headImg":[netdata objectForKey:@"URL"]};
                
                [MBProgressHUD showHUDAddedTo:ctl.view animated:YES];
                
                [DE serverCall:@"updateHeadImg" params:params callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
                    [MBProgressHUD hideHUDForView:ctl.view animated:YES];
                    if(success && [data objectForKey:@"result"])
                    {
                        [ctl.headImage setImage:image];
                    }
                }];
            }
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:success?@"更新头像成功!":@"更新头像失败！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];

        }];
        
    };
    
    [_takephoto startTakePhotoFromViewControl:kAppDelegate.iCSDrawerController];

}
-(void)addbuttonviewbtn:(id)sender
{
    _ispulldown = NO;
    [_addbuttonview removeFromSuperview];
}
-(void)showRightBtnView:(id)sender
{
    if (_ispulldown == NO) {
        [self.view addSubview:_addbuttonview];
        _ispulldown = YES;
    }else
    {
        _ispulldown = NO;
        [_addbuttonview removeFromSuperview];
    }
}
- (void)chooseBtn:(UIButton*)btn
{
    if (btn.tag == 0) {
        //创建群
        _ispulldown = NO;
        [_addbuttonview removeFromSuperview];
        CreateGroupViewController * groupCreate = [[CreateGroupViewController alloc] init];
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:groupCreate animated:NO];
    }
    else if (btn.tag == 1) {
        //创建讨论组
        _ispulldown = NO;
        [_addbuttonview removeFromSuperview];
        selectMemberViewController * chatCreate = [[selectMemberViewController alloc] init];
        NSMutableSet *selectedContact = [[NSMutableSet alloc]init];
        chatCreate.selectedContact = selectedContact;
        chatCreate.CreateType =CREATETYPE_CREATECHAT;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:chatCreate animated:NO];
    }
    else if (btn.tag == 2) {
        _ispulldown = NO;
        [_addbuttonview removeFromSuperview];
        
        AddFriendViewController * addfriend = [[AddFriendViewController alloc] init];
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:addfriend animated:NO];
    }
    else if (btn.tag == 3) {
        _ispulldown = NO;
        [_addbuttonview removeFromSuperview];
        ZbarReaderViewController * scanning = [[ZbarReaderViewController alloc] init];
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:scanning animated:NO];
    }
    else if (btn.tag == 4) {
        _ispulldown = NO;
        [_addbuttonview removeFromSuperview];
        FeedbackViewController * feedback = [[FeedbackViewController alloc] init];
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:feedback animated:NO];
    }

}

-(void)refreshAdBookForced
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [DE serverCall:@"refreshAdBookForced" params:[[NSDictionary alloc] init] callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param)
     {
         
         dispatch_async(dispatch_get_main_queue(), ^{
             [MBProgressHUD hideHUDForView:self.view animated:YES];
             
             if (success) {
                 // 优先更新通讯录
                 NSDictionary* txl = [data objectForKey:@"txl"];
                 if (txl!=nil) {
                     NSString *txlVersion = [txl objectForKey:@"version"];
                     [DE setGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]] value:txlVersion];
                     NSArray * txlls = [txl objectForKey:@"updates"];
                     [ContactDao updataDBwithSQLiteStatement:txlls clearFisrt:YES];
                     
                     [[NSNotificationCenter defaultCenter] postNotificationName:CONTACT_CHANGE_BROADCAST object:nil];
                     
                 }
             }
             
            UIAlertView * aler =  [[UIAlertView alloc] initWithTitle:@"提示" message:success?@"更新通讯录成功！":@"更新通讯录失败！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [aler show];
         });
         
     }];
}

@end
